<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use DB;
use App\Http\Controllers\common\MyAgentController;
use App\Http\Controllers\Controller;
use App\Http\Controllers\admin\VoiceController;

class GatewayController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    static $allGateway = [];

    public function getIndex(Request $request)
    {
        $where = array();
        $get = array();
        $agentId = $request->cookie('agentId');
        $page = $request->input('page',1);
        $get['eui'] = $request->input('eui','');
        $get['name'] = $request->input('name','');
        $get['ag'] = $request->input('ag',$agentId);
        if($get['eui']){
            $where['bs_eui'] = $get['eui'];
        }
        $where['bs_agent_id'] = $get['ag'];
        /*代理商下拉菜单-----始*/
        //查询父级代理商path
        $path = DB::table('sa_agent') -> select('path') -> where(['id'=>$agentId]) -> first();
        $len = substr_count($path['path'],',');
        $agent = MyAgentController::allAgent($agentId);
        foreach ($agent as $k=>$v){
            $agent[$k]['agent_name'] = str_repeat('--',substr_count($v['path'],',')-$len)."<img src='/admin/images/company.png'>&nbsp;&nbsp;".$v['agent_name'];
        }
        /*代理商下拉菜单-----末*/
        /*网关记录-----始*/
        $rows = DB::table('sa_base_station') -> where($where) -> where('bs_name','like','%'.$get['name'].'%') -> paginate(1);
        if(empty(self::$allGateway)){
            self::$allGateway = DB::table('sa_base_station') -> where($where) -> where('bs_name','like','%'.$get['name'].'%') -> get();
        }
        //dd($res);
        $online = [];
        $offline = [];
        $others = [];
        foreach (self::$allGateway as $k=>$v){
            $status = $this -> getGatewayStatus($v['bs_eui']);
            $v['bs_status'] = $status;
            if($status == 1){
                $online[] = $v;
            }elseif ($status == 0){
                $offline[] = $v;
            }else{
                $others[] = $v;
            }
        }
        $all = array_merge($online,$offline,$others);
        $start = ($page-1)*1;
        $res = array_slice($all,$start,1);
        /*网关记录-----末*/
        return view('admin.gateway.index',['agent'=>$agent,'res'=>$res,'data'=>$rows,'request'=>$request->all(),'get'=>$get]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getCreate()
    {
        $data = DB::table('sa_gateway') ->select('t_model','tp_id') ->where('t_type','gateway') -> get();
        // dd($data);
        return view('admin.gateway.create',['data'=>$data]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postStore(Request $request)
    {
        $info = array();
        $data = $request -> except('_token');
        foreach($data as $v){
            if(empty($v)){
                return back() -> withInput() -> with('error','添加失败,请填写完整');
            }
        }
        $info['bs_eui'] = $data['gataway_id'];
        $info['bs_name'] = $data['tb_name'];
        $info['bs_model'] = $data['model'];
        $info['bs_txpower'] = $data['txpower'];
        $info['longitude'] = $data['long'];
        $info['latitude'] = $data['lat'];
        $info['bs_add_time'] = date('Y-m-d H:i:s',time());
        $info['bs_height'] = $data['height'];
        $info['bs_status'] = $data['status'];
        // $info['bs_agent_id'] = session('agentId');
        $info['bs_agent_id'] = $request->cookie('agentId');
        //将网关信息插入lora
        $lora = new LoraController();
        $msg = $lora -> addGateway($data['tb_name'],$data['gataway_id'],$data['model'],$data['txpower']);
        $msg = json_decode($msg,true);
        if($msg['code'] == 1 || $msg['info']){
            //lora插入成功, 查询网关是否在iot已存在
            $res = DB::table('sa_base_station') -> where('bs_eui','=',$info['bs_eui']) -> first();
            if($res){
                return back() -> withInput() -> with('error','iot系统中网关已存在,请勿重复添加');
            }else{
                $rows = DB::table('sa_base_station') -> insert($info);
                if($rows){
                    return redirect('/admin/gateway/index') -> with('success','添加成功');
                }else{
                    return back() -> withInput() -> with('error','添加失败');
                }
            }
        }else{
            return back() -> withInput() -> with('error',$msg['info']);
        }
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function getEdit(Request $request)
    {
        $where = array();
        $where['bs_eui'] = $request -> input('id'); 
        $info = DB::table('sa_base_station')
            -> where($where)
            -> first();
        $data = DB::table('sa_gateway') ->select('t_model','tp_id') ->where('t_type','gateway') -> get();
        return view('admin.gateway.edit',['data'=>$data,'info'=>$info]);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function postUpdate(Request $request)
    {
        $gateway_id = trim($request->input('gataway_id'));
        $data = $request -> except('_token','gataway_id');
        // dd($data);
        $info['bs_name'] = trim($data['tb_name']);
        $info['bs_model'] = $data['model'];
        $info['bs_txpower'] = $data['txpower'];
        $info['longitude'] = $data['long'];
        $info['latitude'] = $data['lat'];
        $info['bs_height'] = $data['height'];
        $info['bs_status'] = $data['status'];
        if($request -> input('long')){
            $data['b_longitude'] = $request -> input('long');
        }
        if($request -> input('lat')){
            $data['b_latitude'] = $request -> input('lat');
        }
        $rows = DB::table('sa_base_station') -> where('bs_eui','=',$gateway_id) -> update($info);
        if($rows){
            return redirect('/admin/gateway/index') -> with('success','修改成功');
        }else{
            return back() -> withInput() -> with('error','修改失败');
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function getDestroy(Request $request)
    {
        $gatewayId = $request->input('id');
        //删除lora的网关记录
        $lora = new LoraController();
        $lora->delGateway($gatewayId);
        //删除本地网关
        $row = DB::table('sa_base_station')->where(['bs_eui' => $gatewayId])->delete();
            if ($row) {
                return redirect('/admin/gateway/index')->with('success', '删除成功');
            } else {
                return back()->withInput()->with('error', '删除失败');
            }
    }

    public function getGatewayStatus($gw_id){
        $lora = new LoraController();
        $res = $lora -> getGatewayMsg($gw_id);
        $res = json_decode($res,true);
        if(isset($res['data'])){
            return $res['data']['state'] ;
        }else{
            return false;
        }
    }
}
